<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="6" :sm="24">
            <a-form-item label="版本">
              <a-select @change="versionChange" v-model="queryParam.version_id" placeholder="请选择"
                        allowClear >
                <a-select-option v-for="(version,index) in subjectTree" :value="version.id" :key="index">{{version.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="学科">
              <a-select @change="subjectChange"  v-model="queryParam.subject_id" placeholder="请选择"
                        allowClear >
                <a-select-option v-for="(subject,index) in subjectOptions" :value="subject.id" :key="index">{{subject.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" >新建</a-button>
    </div>
    <template>
      <a-table ref="table"
               :columns="columns"
               rowKey="id"
               :dataSource="treeList"
      >
        <span slot="action" slot-scope="text, record">
        <template >
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleAdd(record)">新增子分类</a>
          <a-divider type="vertical" />
            <a-popconfirm title="确定删除分类吗" @confirm="deleteCate(record)"  okText="确定" cancelText="取消">
    <a href="javascript:;">删除</a>
  </a-popconfirm>
        </template>
      </span>
      <span slot="name" slot-scope="name,record">
          <span v-if="record.status==1">{{record.name}}</span>
          <span v-else style="color: #999">{{record.name}}</span>
      </span>
      <span slot="status" slot-scope="status,record">
        <a-badge status="success" v-if="status==1" text="显示" />
        <a-badge status="default" v-else text="隐藏" />
      </span>

        <span slot="rank" slot-scope="text,record">
        <template >
        <editable-cell :text="text" @change="onRankChange(record.id, 'rank', $event)"/>
        </template>
      </span>


      </a-table>
    </template>
    <a-modal
      title="操作"
      :width="800"
      v-model="visible"
      @ok="handleOk"
    >
      <a-spin :spinning="saveLoading">
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="上级分类"
          v-if="!formData.id"
          hasFeedback
        >
          <a-cascader :options="options"
                      placeholder="顶级分类"
                      changeOnSelect
                      v-model="formData.parents_ids"
                      :fieldNames = "{ label: 'title', value: 'key', children: 'children' }"
          />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="名称"
          hasFeedback
        >
          <a-input v-decorator="[
          'name',
          {rules: [{ required: true, message: '请输入分类名称' }]}
        ]"
         placeholder="请输入分类名称"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="状态"
          hasFeedback
        >
          <r-switch  :formData="formData" field="status" :checkedValue="1" :unCheckedValue="2"  checkedChildren="显示" unCheckedChildren="隐藏" />
        </a-form-item>
        <a-form-item
                v-if="formData.id"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="排序"
                hasFeedback
        >
          <a-input type="number" v-decorator="[
          'rank',
          {rules: [{ required: true, message: '请输入排序' }]}
        ]"
                   placeholder="数字越小排名越靠前"/>
        </a-form-item>

      </a-form>
        </a-spin>
      <template slot="footer">
        <a-button key="cancel" @click="handleCancel">取消</a-button>
        <a-button key="forward" :loading="saveLoading" type="primary" @click="handleOk">保存</a-button>
      </template>
    </a-modal>

  </a-card>
</template>

<script>
  import moment from 'moment'
  import EditableCell from '@/components/EditableCell/'
  import { getCateTreeList,editCate,addCate,deleteCate,getCateDetail,getCateList,setCateRank ,getSubjectTree } from '@/api/subject'
  import PicUploader from '@/components/PicUploader/'
  import RSwitch from '@/components/RSwitch/'

  export default {
    name: 'SubjectCateList',
    components: {
      PicUploader,EditableCell,RSwitch
    },
    data () {
      return {
        saveLoading:false,
        visible: false,
//        description: '全校班级管理。',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12 },
        },
        form: this.$form.createForm(this),
        mdl: {},

        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {
        },
        // 表头
        columns: [
          {
            title: '名称',
            dataIndex: 'name',
            scopedSlots: { customRender: 'name' },
          },
          {
            title: '状态',
            dataIndex: 'status',
            scopedSlots: { customRender: 'status' },
          },
          {
            title: '排序',
            dataIndex: 'rank',
            scopedSlots: { customRender: 'rank' },
          },
          {
            table: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: { customRender: 'action' },
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          console.log('loadData');
        },
        treeList:[

        ],
        cateList:[

        ],
        versionOptions:[

        ],
        subjectOptions:[

        ],
        subjectTree:[

        ],
        formData:{
          name:'',
          parents_ids:[],
          id:0,
          status:1,
        },
        selectedRowKeys: [],
        selectedRows: [],
      }
    },
    created () {
//      getRoleList({ t: new Date()})
    },
    computed:{
      options (){
        return  this.treeList;
      }
    },
    mounted(){
    let that = this;
      getSubjectTree().then(res => {
        that.subjectTree =  res.data
        that.subjectOptions =  that.subjectTree[0].children;
        that.queryParam.version_id =that.subjectTree[0].id;
        that.queryParam.subject_id =that.subjectTree[0].children[0].id;
        that.fetch();
      })
    },
    methods: {
      fetch(){
        let that = this;
        getCateTreeList(that.queryParam)
            .then(res => {
              that.treeList =  res.data;
            })
//        getCateList()
//            .then(res => {
//              that.cateList =  res.data
//            })
      },
      versionChange(version_id){
        let that = this;
        console.log('versionChange',version_id);
        let currentVersion = that.subjectTree.filter(item =>{
          return item.id == version_id
        });
        console.log('currentVersion',currentVersion);
        that.subjectOptions =  currentVersion[0].children;
        that.queryParam.subject_id = undefined;
      },
      subjectChange(){
        this.fetch();
      },
      handleCancel(){
        this.visible = false
      },
     // 增
    handleAdd(record) {
      let that = this;
      that.visible = true;
      that.form.resetFields();
      that.formData = {
        name:'',
        parents_ids:[],
        id:0,
        status:1,
      }
      if(record.id){
        that.formData.parents_ids = that.cateParentsIds(record.id);
        that.formData.parents_ids.push(record.id+'');
      }
      setTimeout( () =>{
        that.form.setFieldsValue({ ...that.formData });
      });
    },
    // 改
    handleEdit(record) {
      let self = this
      this.visible = true
//      this.form.resetFields();
      self.form.setFieldsValue({
        name:'',
        rank:0,
      });
      this.formData.id = record.id;
      getCateDetail({ id: record.id }).then(res => {
        setTimeout(()=>{
          self.form.setFieldsValue({...res.data});
        },1)
        self.formData.name = res.data.name;
        self.formData.parents_ids = self.cateParentsIds(record.id);
        self.formData.status = res.data.status ;
      })
      // console.log(this.mdl)
    },
    // 增改 处理
    handleOk(e) {
      let self = this
      e.preventDefault()
      if(!self.queryParam.subject_id){
        self.$message.error('请先选择学科');
        return ;
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          self.formData.subject_id = self.queryParam.subject_id;
          console.log('Received values of form: ', values)
          console.log('Received valuess of formData: ', self.formData)
          self.saveLoading = true;
          if(self.formData.id) {
            editCate(Object.assign(self.formData,values)).then(res => {
              self.$message.success('修改成功')
              self.fetch();
              self.visible = false;
              self.saveLoading = false;
            }).catch(err =>{
              self.$message.error(err.data.msg);
              self.saveLoading = false;
            })
          }else{
            addCate(Object.assign(self.formData,values)).then(res => {
              self.$message.success('新增成功')
              self.fetch();
              self.visible = false
              self.saveLoading = false;
            }).catch(err =>{
              self.$message.error(err.data.msg);
              self.saveLoading = false;
            })
          }
        }
      })
    },
     // 删
      deleteCate(record) {
        let self = this
        deleteCate({ id: record.id  }).then(res => {
          self.$message.success('删除成功')
          self.fetch();
      }).catch(err =>{
          self.$message.error(err.data.msg)
        })
    },
      cateParentsIds(cate_id){
        let self = this;
        let parent_id = cate_id;
        let parents_ids = [];
        while(parent_id != 0){
          cate_id = parent_id;
          parent_id = self.getListParentId(cate_id);
          if(parent_id >0){
            parents_ids.push(parent_id+'');
            continue;
          }
          break;
        }
        return parents_ids.reverse(parents_ids);
      },
      getListParentId(cate_id){
        let self = this;
        let parent_id = 0;
        self.cateList.map(function (item) {
          if(item.id == cate_id){
            parent_id = item.parent_id
            return ;
          }
        })
        return parent_id;
      },

      onRankChange(key, dataIndex, value) {
        let self = this;
        setCateRank({
          id: key,
          rank:value
        }).then(res => {
          self.fetch();
        }).catch(err =>{
          self.$message.error(err.data.msg)
        })
      },
    },
    watch: {
      /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
    }
  }
</script>